﻿using System;
using NUnit.Framework;
using VegetableSale.NET.Dao;
using VegetableSale.NET.Entities;

namespace VegetableSale.NET.Services;

public class RtsaleService
{
    private RtsaleMapper rtsaleMapper = new RtsaleMapper();

    private GoodService goodService = new GoodService();

    private SaleMapper saleMapper = new SaleMapper();

    private SaleService saleService = new SaleService();

    public Result getRtsaleList(QueryDTO queryDTO)
    {
        RtsalePage rtsalePage = new RtsalePage();
        uint pageNo = queryDTO.PageNo;
        uint pageSize = queryDTO.PageSize;

        List<Rtsale> rtsales = rtsaleMapper.getRtsaleList(queryDTO);
        List<Rtsale> returnRtsales = new List<Rtsale>();

        if (pageSize * pageNo - 1 >= rtsales.Count)
        {
            for (uint i = pageSize * (pageNo - 1); i <= rtsales.Count - 1; i++)
            {
                Rtsale rtsale = rtsales[(int) i];
                returnRtsales.Add(rtsale);
            }
        }
        else
        {
            for (uint i = pageSize * (pageNo - 1); i <= pageSize * pageNo - 1; i++)
            {
                Rtsale rtsale = rtsales[(int) i];
                returnRtsales.Add(rtsale);
            }
        }

        rtsalePage.Records = returnRtsales;
        rtsalePage.Pages = (int) pageNo;
        rtsalePage.Size = pageSize;
        rtsalePage.Total = (uint) rtsales.Count;

        return new Result(200, "搜索成功", rtsalePage);
    }

    public Result addRtsale(RtsaleQuery rtsaleQuery)
    {
        goodService.updateInventory(rtsaleQuery.Commid, rtsaleQuery.Rtsnumber, "+");

        int newSaleMount = rtsaleQuery.Salemount - rtsaleQuery.Rtsnumber;
        int newSaleMoney = newSaleMount * rtsaleQuery.Salemoney;
        if (newSaleMount <= 0)
        {
            newSaleMount = 0;
            saleService.deleteSale(rtsaleQuery.Id);
        }

        saleMapper.updateSaleMount(rtsaleQuery.Id, newSaleMount, newSaleMoney);
        rtsaleMapper.addRtsale(rtsaleQuery);
        return new Result(200, "操作成功", "");
    }
}